import { defineComponent, ref, watch, reactive, CSSProperties } from 'vue'
import { ColumnType, PaginationType } from './type'
import PropTypes from '@/utils/PropTypes'
import { message, Table } from 'ant-design-vue'
type scrollType =
  | {
      x?: number | string | true
      y?: number | string
    }
  | undefined
type rowClassNameType = {
  index: string | number
  className: string
} | null
export default defineComponent({
  name: 'TableCom',
  props: {
    rowKey: PropTypes.string().def('id'),
    childrenColumnName: PropTypes.string().def(''),
    rowSelection: PropTypes.bool().def(false),
    bordered: PropTypes.bool().def(false),
    rowSelectionType: PropTypes.anyOption<'checkbox' | 'radio'>().def(
      'checkbox',
    ),
    disableSelectKeys: PropTypes.object().def({
      key: '',
      subkey: '',
      subkeyValue: '',
    }),
    selectedRowKeys: PropTypes.array<number | string>().def([]),
    expandedRowKeys: PropTypes.array<string>().def([]),
    columns: PropTypes.array<ColumnType>().def([]),
    dataSource: PropTypes.array<any>().def([]),
    pagination: PropTypes.any().def(),
    handleTableChange: PropTypes.func<(e: any) => void>(),
    emptyText: PropTypes.any(),
    justifyContent: PropTypes.string().def('flex-start'),
    tableBoxStyle: PropTypes.object<any>().def({
      width: '100%',
      backgroundColor: '#fff',
    }),
    padding: PropTypes.number().def(0),
    showSizeChanger: PropTypes.bool().def(true),
    showQuickJumper: PropTypes.bool().def(true),
    scroll: PropTypes.anyOption<scrollType>().def(undefined),
    tableBodyStyle: PropTypes.object<CSSProperties>().def({ margin: '10px 0' }),
    rowClassName: PropTypes.anyOption<rowClassNameType | null>(),
  },
  emits: ['update:selectedRowKeys', 'update:expanded', 'update:selectedRows'],
  setup(props, { slots, emit }) {
    type Key = string | number
    const loading = ref<boolean>(false)
    const expandedRowKeys = ref<string[]>([])
    const tableStyle = {
      width: '100%',
      backgroundColor: '#fff',
      padding: props.padding + 'px',
      boxSizing: 'border-box',
      ...props.tableBoxStyle,
    }
    // 表格选择
    const state = reactive<{
      selectedRowKeys: Key[]
    }>({
      selectedRowKeys: props.selectedRowKeys || [], // Check here to configure the default column
    })

    const filterSelectRowKeys = (selectedRowKeys: Key[], selectedRows: any) => {
      const { key, subkey, subkeyValue } = props.disableSelectKeys
      selectedRows.forEach((item: any) => {
        if (item[key]) {
          if (item[subkey] == subkeyValue) return
          const index = selectedRowKeys.findIndex(
            (item: any) => item === item[props.rowKey],
          )
          message.error(`${item[key]}商品已销售，不能选择!`)
          selectedRowKeys.splice(index, 1)
        }
      })
      return selectedRowKeys
    }

    const onSelectChange = (selectedRowKeys: Key[], selectedRows: any) => {
      // console.log('selectedRowKeys changed: ', selectedRowKeys)
      selectedRowKeys = filterSelectRowKeys(selectedRowKeys, selectedRows)
      state.selectedRowKeys = selectedRowKeys
      emit('update:selectedRowKeys', state.selectedRowKeys)
    }
    const expand = (expanded: boolean, record: any) => {
      console.log(expanded, record, 'ooo')
      // emit('update:expandedRowKeys', expandedRowKeys.value)
    }

    const onSelect = (record: any, selected: any) => {
      selected || emit('update:selectedRows', record)
    }
    // 行样式
    const getRowClassName = (record: any, _index: number) => {
      if (!props.rowClassName) return ''
      const { index, className } = props.rowClassName!
      if (index && props.dataSource.length - 1 == _index) {
        return className
      }
      return ''
    }
    watch(
      () => props.dataSource,
      () => {
        loading.value = props.dataSource!.length >= 0 ? false : true
      },
    )
    watch(
      () => props.selectedRowKeys,
      () => {
        state.selectedRowKeys = props.selectedRowKeys
      },
    )
    watch(
      () => props.expandedRowKeys,
      () => {
        expandedRowKeys.value = props.expandedRowKeys
      },
    )
    watch(
      () => expandedRowKeys.value,
      () => {
        emit('update:expanded', expandedRowKeys.value)
      },
    )
    return () => (
      <div style={tableStyle}>
        {slots.form?.()}
        <Table
          v-model:expandedRowKeys={expandedRowKeys.value}
          style={props.tableBodyStyle}
          columns={props.columns}
          childrenColumnName={props.childrenColumnName}
          row-key={(record: any) => record[props.rowKey]}
          bordered={props.bordered}
          data-source={props.dataSource}
          rowClassName={getRowClassName}
          pagination={
            props.pagination && {
              ...props.pagination,
              showSizeChanger: props.showSizeChanger,
              showQuickJumper: props.showQuickJumper,
            }
          }
          locale={{
            emptyText: props.emptyText,
          }}
          loading={loading.value}
          onChange={props.handleTableChange}
          onExpand={expand}
          row-selection={
            props.rowSelection
              ? {
                  selectedRowKeys: state.selectedRowKeys,
                  type: props.rowSelectionType,
                  fixed: true,
                  onChange: onSelectChange,
                  onSelect: onSelect,
                }
              : null
          }
          v-slots={{
            footer: slots.footers?.() ? () => slots.footers?.() : null,
            summary: slots.summerys?.()
              ? (currentRow: any) => slots.summerys?.(currentRow)
              : null,
          }}
          scroll={props.scroll}
        ></Table>
      </div>
    )
  },
})
